new Vue({
    el: '#app',
    data() {
        return {
            loading:true,
            showCart: false,
            products:{},
            cart:{}
        };
    },
    methods: {
        handleChange(value) {
            console.log(value);
        },
        getProducts(){
            let thisApp = this;
            thisApp.loading = true;
            axios.get(apiGetProducts).then(function (response) {
                let rawProducts = response.data;
                let tranProducts = {};
                /*将商品ID转化为数组索引*/
                for(let i in rawProducts)
                {
                    tranProducts[rawProducts[i].id]=rawProducts[i];
                }
                /* 使用过渡性变量[tranProducts]进行中间处理，然后一次性赋值给app变量[thisApp.products] */
                thisApp.products = tranProducts;
                thisApp.loading = false;
            }).catch(function (error) {
                alert('Error! Could not reach the API. ');
                console.log(error);
            });
        },
        getCart(){
            //所有异步请求都必须让加载动画显示
            this.loading = true;
            let thisApp = this;
            axios.get(apiGetCart).then(function (response) {
                if(response.data.status==='101')
                {
                    alert('请先登录');
                    return;
                }
                let rawCart = response.data;
                let tranCart = {};
                for(let i in rawCart)
                {
                    tranCart[rawCart[i].product_id]=rawCart[i];
                }
                thisApp.cart = tranCart;
                thisApp.loading = false;
            }).catch(function (error) {
                alert('Error! Could not reach the API. ');
                console.log(error);
            });
        },
        updateCart(tranCartProduct,addOrSub){
            this.loading = true;
            let thisApp = this;
            tranCartProduct.countType = addOrSub;
            axios.post(apiUpdateCart,tranCartProduct).then(function (response) {
                if(response.data.status==='101')
                {
                    alert('请先登录');
                    thisApp.loading = false;
                    return;
                }
                console.log(response.data); //高度输出更新后的数量
                thisApp.getCart();
            }).catch(function (error) {
                alert('Error! Could not reach the API. ');
                console.log(error);
            });
        },

    },
    computed:{
        total: function () {
            let total = {price:0,quantity:0};
            for(let i in this.cart)
            {
                total.price += this.cart[i].product.product_price * this.cart[i].quantity;
                total.quantity += parseInt(this.cart[i].quantity);
            }
            return total;
        },

    },
    mounted () {
        this.getProducts();
        this.getCart();
    }
});
